<template>
	<view class="mx-2">
		<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
			<image class="avatar" :src="userAvatarUrl"></image>
		</button>
		<input class="nickname" type="nickname" v-model="userNickName" @change="getNickname" placeholder="请输入昵称" />
		<button @click="login">登录</button>
	</view>
</template>


<script>
	import {
		jsCodeByOpenid,updateUser
	} from "@/common/api/user.js"
	const defaultAvatarUrl =
		'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
	export default {
		data() {
			return {
				openid: "",
				userAvatarUrl: defaultAvatarUrl,
				userNickName: "",
				form:{
					code: "",
					userAvatarUrl: "",
					userNickName: "",
				}
			}
		},
		created() {

		},
		methods: {
			onChooseAvatar(e) {
				const {
					avatarUrl
				} = e.detail
				this.userAvatarUrl = avatarUrl
			},
			getNickname(e){
			   this.userNickName = e.detail.value
			},
			login() {
				let that = this;
				if(that.userNickName ==""){
					uni.showToast({
						title:"用户昵称不能为空",icon:"none"
					})
					return false
				}
				uni.login({
					provider: 'weixin',
					success: res => {
						let code = res.code
						that.form.code = code;
						that.form.userAvatarUrl = that.userAvatarUrl;
						that.form.userNickName = that.userNickName;
						jsCodeByOpenid(that.form).then(res => { 
						
							if (res.code == 200) {
								uni.showToast({
									title: res.message,
									icon: "none"
								}) 
								that.form.openid =  res.result.openid || JSON.parse(res.result).openid;
							
								updateUser(that.form).then(ret => {
									uni.setStorageSync("token", ret.result.token)
									uni.setStorageSync("openid", ret.result.openid)
									uni.setStorageSync("userInfo", ret.result.userInfo)
								})	 
								setTimeout(function() {
									uni.switchTab({
										url: "/pages/chasing/index"
									})
								}, 2000)
							} else {
								uni.showToast({
									title: res.message,
									icon: "none"
								})
							}
						})
					}
				});

			}
		}
	}
</script>


<style>
	.nickname{border: solid 1px #c1bebe;}
</style>